package me.exchange.com.modules.system.controller;

import cn.hutool.core.lang.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.exchange.com.aop.log.Log;
import me.exchange.com.exception.BadRequestException;
import me.exchange.com.modules.system.domain.Menu;
import me.exchange.com.modules.system.domain.Role;
import me.exchange.com.modules.system.dto.RoleDto;
import me.exchange.com.modules.system.dto.RoleQueryCriteria;
import me.exchange.com.modules.system.dto.RoleSmallDto;
import me.exchange.com.modules.system.dto.UserDto;
import me.exchange.com.modules.system.service.RoleService;
import me.exchange.com.modules.system.service.UserService;
import me.exchange.com.utils.Result;
import me.exchange.com.utils.SecurityUtils;
import me.exchange.com.utils.ThrowableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@Api(tags = "系统：角色管理")
@RestController
@RequestMapping("/api/roles")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    private static final String ENTITY_NAME = "role";

    @ApiOperation("获取单个role")
    @PostMapping(value = "/queryInfo")
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> getRoles(Long id){
       RoleDto role = roleService.findById(id);
        return new ResponseEntity<>(Result.ok("角色详情查询成功").put("role",role), HttpStatus.OK);
    }

    @Log("导出角色数据")
    @ApiOperation("导出角色数据")
    @PostMapping(value = "/list/download")
    @PreAuthorize("@el.check('role:list')")
    public void download(HttpServletResponse response, RoleQueryCriteria criteria) throws IOException {
        roleService.download(roleService.queryAll(criteria), response);
    }

    @ApiOperation("返回全部的角色")
    @PostMapping(value = "/all")
    @PreAuthorize("@el.check('roles:list','user:add','user:edit')")
    public ResponseEntity<Object> getAll(@PageableDefault(value = 2000, sort = {"level"}, direction = Sort.Direction.ASC) Pageable pageable){
        RoleQueryCriteria criteria =  new RoleQueryCriteria();
        Object role = roleService.queryAll(criteria);
        return new ResponseEntity<>(Result.ok("全部的角色查询成功").put("roles",role),HttpStatus.OK);
    }

    @Log("查询角色")
    @ApiOperation("查询角色")
    @PostMapping("/list")
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> getRoles(RoleQueryCriteria criteria, Pageable pageable){
        if(criteria.getCAdminTime() != null && criteria.getCAdminTime().size()>0){
            if(criteria.getCAdminTime().get(1).before(criteria.getCAdminTime().get(0))){
                return new ResponseEntity<>(Result.error("操作失败，查询时间段设置不正确"),HttpStatus.OK);
            }
        }
        List<RoleDto> listRole= roleService.queryAll(criteria);
        return new ResponseEntity<>(Result.ok("角色列表查询成功").put("roleList",listRole),HttpStatus.OK);
    }
    @Log("查询角色下拉列表")
    @ApiOperation("查询角色下拉列表")
    @PostMapping("/roleSelect")
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<Object> getAllDepts(RoleQueryCriteria criteria){
        List<RoleDto> roleDtos = roleService.queryAll(criteria);
        return new ResponseEntity<>(Result.ok("角色下拉查询成功").put("roleList",roleDtos),HttpStatus.OK);
    }
    @ApiOperation("获取用户级别")
    @PostMapping(value = "/level")
    public ResponseEntity<Object> getLevel(){
        return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK);
    }

    @Log(value="新增角色",code="system_role")
    @ApiOperation("新增角色")
    @PostMapping("/add")
    @PreAuthorize("@el.check('roles:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Role resources){
        if (resources.getId() != null) {
            return new ResponseEntity<>(Result.error("角色新增失败"),HttpStatus.OK);
        }
        if(roleService.findByRoleName(resources.getRoleName()) != null){
            return new ResponseEntity<>(Result.error("角色新增失败"),HttpStatus.OK);
        }
        getLevels(resources.getLevel());
        roleService.create(resources);
        return new ResponseEntity<>(Result.ok("角色新增成功"),HttpStatus.OK);
    }

    @Log(value="修改角色",code="system_role")
    @ApiOperation("修改角色")
    @PostMapping("/update")
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> update(@Validated(Role.Update.class) @RequestBody Role resources){
        getLevels(resources.getLevel());
        roleService.update(resources);
        return new ResponseEntity<>(Result.ok("角色修改成功"),HttpStatus.OK);
    }

    @Log(value="修改角色菜单",code="system_role")
    @ApiOperation("修改角色菜单")
    @PostMapping(value = "/menu")
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> updateMenu(@RequestParam(value="id") Long id,@RequestParam("menus") String menus ){
        Set<Menu> menuSet = new HashSet<>();
        String[] me = menus.split(",");
        for (String m:me) {
            Menu menu = new Menu();
            menu.setId(Long.parseLong(m));
            menuSet.add(menu);
        }
        Role resources = new Role();
        resources.setMenus(menuSet);

        RoleDto role = roleService.findById(id);
        getLevels(role.getLevel());
        roleService.updateMenu(resources,role);
        return new ResponseEntity<>(Result.ok("角色菜单修改成功"),HttpStatus.OK);
    }

    @Log(value="删除角色",code="system_role")
    @ApiOperation("删除角色")
    @PostMapping("/del")
    @PreAuthorize("@el.check('roles:del')")
    public ResponseEntity<Object> delete(@RequestBody RoleQueryCriteria criteria){
        for (Long id : criteria.getIds()) {
            RoleDto role = roleService.findById(id);
            getLevels(role.getLevel());
        }
        try {
            roleService.delete(criteria.getIds());
        } catch (Throwable e){
            ThrowableUtil.throwForeignKeyException(e, "所选角色存在用户关联，请取消关联后再试");
        }
        return new ResponseEntity<>(Result.ok("删除角色成功"),HttpStatus.OK);
    }

    /**
     * 获取用户的角色级别
     * @return /
     */
    private int getLevels(Integer level){
        UserDto user = userService.findByName(SecurityUtils.getUsername());
        List<Integer> levels = roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if(level != null){
            if(level < min){
                throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
            }
        }
        return min;
    }
}
